package com.itheima.global;

import com.itheima.po.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//配置全局异常
@RestControllerAdvice
public class ControllerAdivce {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlException(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
//        根据异常信息做解析 拿到‘zhangsan'重复输入数据
        String[] strArr = message.split("");
        if(strArr.length>=2){
           return R.error("用户名"+strArr[2]+"已存在");
        }
        return R.error("未知异常");
    }

    @ExceptionHandler(RuntimeException.class)
    public R<String> sqlException(RuntimeException ex){
        String message = ex.getMessage();
//        根据异常信息做解析 拿到‘zhangsan'重复输入数据
        String[] strArr = message.split("");
        if(strArr.length>=2){
            return R.error("用户名"+strArr[2]+"已存在");
        }
        return R.error("未知异常");
    }
//    瑞吉点菜中 0代表成功，1代表失败
    @ExceptionHandler(RuntimeException.class)
    public R<String> sqlException(BusinessException ex){
        return R.error(ex.getMessage());
    }
}
